const express = require('express')
const router = express.Router()
const rds = require('../tmall-db/rds')
const logger = require('../logger')

// 根路径重定向到默认商户
router.get('/', (req, res) => {
    res.redirect('/apps/helpdesk/totemlife');
});

// 为了方便益生智享平台小程序后台填写减少一个参数给出的便捷入口
router.get('/ihealthify/:mer_id', (req, res) => {
    const merId = req.params.mer_id || 'iheal-9';
    res.redirect(`/apps/helpdesk/${merId}?home=ihealthify`) // 重定向到根路由，带上所有查询参数，注意添加 /apps/helpdesk/ 基础路径
});

// 编辑客服中心配置
router.get('/edit/:mer_code', async (req, res) => {
    try {
        const merCode = req.params.mer_code;
        const [[helpdesk]] = await rds.query('SELECT * FROM mta_helpdesks WHERE mer_code = ?', [merCode]);
        let config = helpdesk ? JSON.parse(helpdesk.content) : {
            merchant_name: '',
            phone: '',
            groups: []
        };
        config.mer_code = merCode; // 确保有mer_code

        res.render('helpdesk/edit', {
            title: helpdesk ? '编辑客服中心配置' : '新建客服中心配置',
            config,
            isNew: !helpdesk
        });
    } catch (err) {
        logger.error('获取客服中心配置失败:', err);
        res.status(500).render('warn', {
            title: '系统错误',
            message: '获取客服中心配置失败',
            description: err.message,
            icon: 'weui-icon-warn weui-icon_msg'
        });
    }
});

// 假设 code16 是字符串类型的数字，如 '55514510810410197'
function decodeKfCode(code16) {
    let chars = [];
    let i = 0;
    while (i < code16.length) {
        // ASCII码最大3位，最小2位（但常用字符都是两位或三位）
        // 先尝试取3位
        let num3 = parseInt(code16.substr(i, 3), 10);
        if (num3 >= 100 && num3 <= 122) { // 常见小写字母/数字/符号
            chars.push(String.fromCharCode(num3));
            i += 3;
        } else {
            // 取2位
            let num2 = parseInt(code16.substr(i, 2), 10);
            chars.push(String.fromCharCode(num2));
            i += 2;
        }
    }
    // 还原倒序
    return chars.reverse().join('');
}

// 简单放君子的编辑客服中心配置
router.get('/jedt/:code16', async (req, res) => {
    const code16 = req.params.code16;
    const merCode = decodeKfCode(code16);
    try {
        const [[helpdesk]] = await rds.query('SELECT * FROM mta_helpdesks WHERE mer_code = ?', [merCode]);
        let config = helpdesk ? JSON.parse(helpdesk.content) : {
            merchant_name: '',
            phone: '',
            groups: []
        };
        config.mer_code = merCode; // 确保有mer_code

        res.render('helpdesk/edit', {
            title: helpdesk ? '编辑客服中心配置' : '新建客服中心配置',
            config,
            isNew: !helpdesk
        });
    } catch (err) {
        logger.error('获取客服中心配置失败:', err);
        res.status(500).render('warn', {
            title: '系统错误',
            message: '获取客服中心配置失败',
            description: err.message,
            icon: 'weui-icon-warn weui-icon_msg'
        });
    }
});

// 保存客服中心配置
router.post('/save', async (req, res) => {
    try {
        // logger.info('收到保存请求，请求体:', JSON.stringify(req.body));
        const mer_code = req.body.mer_code || null;
        let configData = {};
        if (typeof req.body.groups === 'string') {
            try {
                configData = JSON.parse(req.body.groups);
                // logger.info('解析后的配置对象:', JSON.stringify(configData));
            } catch (e) {
                // 只保留必要的错误日志
                logger.error('解析配置对象失败:', e);
                configData = {};
            }
        } else {
            // 只保留必要的错误日志
            logger.error('groups 字段不是字符串，数据异常:', req.body.groups);
            configData = {};
        }
        if (!mer_code) {
            throw new Error('mer_code 不能为空');
        }
        // 检查是否存在
        const [[existing]] = await rds.query('SELECT id FROM mta_helpdesks WHERE mer_code = ?', [mer_code]);
        if (existing) {
            await rds.query(
                'UPDATE mta_helpdesks SET content = ? WHERE mer_code = ?',
                [JSON.stringify(configData), mer_code]
            );
            // logger.info(`更新了客服中心配置 ${mer_code}`);
        } else {
            await rds.query(
                'INSERT INTO mta_helpdesks (mer_code, content) VALUES (?, ?)',
                [mer_code, JSON.stringify(configData)]
            );
            // logger.info(`创建了新的客服中心配置 ${mer_code}`);
        }
        res.redirect(`/apps/helpdesk/ihealthify/${mer_code}`);
    } catch (err) {
        logger.error('保存客服中心配置失败:', err);
        res.status(500).render('warn', {
            title: '系统错误',
            message: '保存客服中心配置失败',
            description: err.message,
            icon: 'weui-icon-warn weui-icon_msg'
        });
    }
});

// 展示所有商户服务台配置列表
router.get('/list', async (req, res) => {
    try {
        const [rows] = await rds.query('SELECT id, mer_code, content FROM mta_helpdesks ORDER BY id DESC');
        // 解析content中的分组和客服摘要
        const configs = rows.map(row => {
            let merchant_name = '', phone = '', groups = [];
            try {
                const c = JSON.parse(row.content || '{}');
                merchant_name = c.merchant_name || '';
                phone = c.phone || '';
                groups = (c.groups || []).map(g => ({
                    group_name: g.group_name,
                    services: (g.services || []).map(s => ({
                        title: s.title,
                        avatar: s.avatar,
                        qrcode: s.qrcode,
                        desc: s.desc
                    }))
                }));
            } catch (e) {}
            return {
                id: row.id,
                mer_code: row.mer_code,
                merchant_name,
                phone,
                groups
            };
        });
        res.render('helpdesk/list', {
            title: '服务台配置列表',
            configs
        });
    } catch (err) {
        logger.error('获取服务台配置列表失败:', err);
        res.status(500).render('warn', {
            title: '系统错误',
            message: '获取服务台配置列表失败',
            description: err.message,
            icon: 'weui-icon-warn weui-icon_msg'
        });
    }
});

// 客服中心页面 - 放在最后，作为默认路由
router.get('/:mer_id', async (req, res) => {
    try {
        const merId = req.params.mer_id;

        // 获取客服中心配置
        const [[helpdesk]] = await rds.query('SELECT * FROM mta_helpdesks WHERE mer_code = ?', [merId]);
        const config = helpdesk ? JSON.parse(helpdesk.content) : null;

        if (!config) {
            return res.status(404).render('warn', {
                title: '未找到配置',
                message: '未找到该商户的客服中心配置',
                description: '请先创建客服中心配置',
                icon: 'weui-icon-warn weui-icon_msg'
            });
        }

        res.render('helpdesk/index', {
            title: config.merchant_name || '客服中心',
            layout: false,
            mer_id: merId,
            config: config
        });
    } catch (err) {
        logger.error('获取客服中心配置失败:', err);
        res.status(500).render('warn', {
            title: '系统错误',
            message: '获取客服中心配置失败',
            description: err.message,
            icon: 'weui-icon-warn weui-icon_msg'
        });
    }
});

module.exports = router
